package com.tyun.modules.sys.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.tyun.common.redis.RedisService;
import com.tyun.common.utils.ResultDTO;
import com.tyun.common.utils.ResultUtil;
import com.tyun.modules.sys.entity.SysUser;
import com.tyun.modules.sys.entity.vo.SysUserInfo;
import com.tyun.modules.sys.service.ISysUserService;
import com.tyun.modules.sys.service.ISysUserTokenService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author taocongcong
 * @create 2017-12-21 16:49
 */
@RestController
@RequestMapping("login")
public class SysLoginController {

    private static final Logger LOGGER = LogManager.getLogger(SysLoginController.class);

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ISysUserTokenService sysUserTokenService;

    /**
     * 用户登录次数计数  redisKey 前缀
     */
    private String SHIRO_LOGIN_COUNT = "shiro_login_count_";

    /**
     * 用户登录是否被锁定    一小时 redisKey 前缀
     */
    // private String SHIRO_IS_LOCK = "shiro_is_lock_";

    @RequestMapping(value = "ajaxLogin")
    public ResultDTO login(HttpServletRequest request, SysUserInfo SysUserInfo){
        // 账号不存在、密码错误
        String username = SysUserInfo.getUsername();
        String password = String.valueOf(SysUserInfo.getUserpassword());
        //校验
        SysUser record = new SysUser();
        record.setUserid(username);
        record.setUserpassword(password);
        SysUser user = null;
        List<SysUser> userList = sysUserService.selectList(new EntityWrapper<>(record).eq("userid", username).eq("userpassword", password));
        if (userList.size() != 0) {
            user = userList.get(0);
        }
        // 从此处开始计算
        // 访问一次计数一次
        redisService.increment(SHIRO_LOGIN_COUNT + username, 1);
        // 此时肯定是密码错误或者其他错误,不做判断
        Integer countLogin = Integer.parseInt(redisService.get(SHIRO_LOGIN_COUNT + username));
        if (user != null) {
            // 分情况
            if (countLogin <= 3) {
                // 登录成功
                // 更新登录时间 last login time
                user.setLoginTime(new Date());
                sysUserService.insertOrUpdate(user);
                // 清空登录计数
                redisService.set(SHIRO_LOGIN_COUNT + username, "0");
                LOGGER.info(user.getUsername() + "于" + new Date() + "登录系统！");
                // 创建token
                ResultDTO r = sysUserTokenService.insertToken(user.getUserid());
                return r;
            }
            redisService.decrBy(SHIRO_LOGIN_COUNT + username, 1);
            countLogin --;
            ResultDTO r = ResultUtil.fail("由于密码输入错误次数大于" + countLogin + "次，帐号已经禁止登录！时间:" + countLogin * 60 + "秒");
            return r;
        }
        if (countLogin < 3) {
            ResultDTO r = ResultUtil.fail("帐号或密码不正确！");
            return r;
        }
        redisService.expire(SHIRO_LOGIN_COUNT + username, 60 * countLogin);
        ResultDTO r = ResultUtil.fail("由于密码输入错误次数大于" + countLogin + "次，帐号已经禁止登录！时间:" + countLogin * 60 + "秒");
        return r;
        /*
        if (StringUtils.equals("LOCK", redisService.get(SHIRO_IS_LOCK + username))) {
            // throw new DisabledAccountException("由于密码输入错误次数大于3次，帐号已经禁止登录！");
            ResultDTO r = ResultUtil.fail("由于密码输入错误次数大于3次，帐号已经禁止登录！时间:" + countLogin * 60 + "秒");
            return r;
        }*/

    }
}
